package com.wolf.cx330.view.act

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Layout
import android.text.method.ScrollingMovementMethod
import android.view.ViewTreeObserver
import android.widget.TextView
import com.wolf.cx330.R
import kotlinx.android.synthetic.main.activity_auto_scroll_text.*
import java.util.*

/**
 * 自动上下滑动的TextView
 */
class AutoScrollTextAct : AppCompatActivity() {
    companion object {
        fun actionStart(context: Context) =
            context.startActivity(Intent(context, AutoScrollTextAct::class.java))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_auto_scroll_text)
        //  TextView 自动滑动
        aasTv.movementMethod = ScrollingMovementMethod.getInstance()

        aasTv.viewTreeObserver
            .addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    aasTv.viewTreeObserver.removeOnGlobalLayoutListener(this)

                }
            })
        Timer().schedule(object : TimerTask() {
            override fun run() {
                runOnUiThread {
                    if (aasTv.scrollY > (getTextViewHeight(aasTv)-aasTv.height)){
                        println("【IM】MainActivity  run: 不允许滑动了!!!!!")
                    }else{
                        aasTv.scrollBy(0, 20)
                    }
                }
            }
        }, 1000, 50)
    }
    /**
     * 获取TextView 所有字高度
     */
    private fun getTextViewHeight(tv: TextView): Int {
        val layout: Layout = tv.layout
        val desired: Int = layout.getLineTop(tv.lineCount)
        val padding = tv.compoundPaddingTop + tv.compoundPaddingBottom
        return desired + padding
    }
}